
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router';
import type { Address } from '../../typings'
import ProductCard from '../../components/ProductCardComp/ProductCard.vue';
import OrderAddressee from '../../components/OrderComps/OrderAddressee.vue'
import {  useOrderListStore } from '../../stores/orderList'
import { useCascaderAreaData } from '@vant/area-data';
import { showFailToast, showToast, showSuccessToast } from 'vant';
import 'vant/es/toast/style'
const router = useRouter()
const props = defineProps<{
    list: string
}>()


const curremtList = computed(() => {
    return JSON.parse(props.list)
})

console.log(curremtList.value);

const currentNum = computed(() => {
    let num = 0
    curremtList.value.map(t => {
        num += t.num
    })

    return num
})

const currentPrice = computed(() => {
    let totlePrice = 0
    curremtList.value.map(t => {
        totlePrice += (t.num * t.nowprice)
    })

    return totlePrice
})

// 当前历史地址
const currentAddressList = ref()
onMounted(() => {
    let obj = localStorage.loaclAddress ? JSON.parse(localStorage.loaclAddress) : []
    currentAddressList.value = obj
    currentAddressList.value.map(item => {
        if (item.default) {
            currentDefault.value = item
            currentId.value = item.id
        }
    })
})
// 两个popup的是否显示
const showAddressPopup = ref(false)
const addAddress = ref(false)

// 地区选择<
const show = ref(false);
// 选择地区的数据
const fieldValue = ref('');
const cascaderValue = ref('');
const options = useCascaderAreaData();
// 地区选择完毕
const onFinish = (obj: {
    selectedOptions: Array<{
        text: string
    }>
}) => {
    let selectedOptions = obj.selectedOptions
    show.value = false;
    fieldValue.value = selectedOptions.map((option) => option.text).join('');
    console.log(fieldValue);

};
// 地区选择>
// 收件信息
const addressee = ref()
const telVal = ref()
const detailedAddress = ref()
const currentDefaultVal = ref(false)

const addAddressFn = () => {

    if (!addressee.value && !telVal.value && !detailedAddress.value && !fieldValue.value) {
        showFailToast('请填写完毕');
        return
    }

    let addressList = localStorage.loaclAddress ? JSON.parse(localStorage.loaclAddress) : []
    let objList = {
        fieldValue: fieldValue.value,
        addressee: addressee.value,
        telVal: telVal.value,
        detailedAddress: detailedAddress.value,
        default: currentDefaultVal.value,
        id: Date.now()
    }
    addressList = addressList.filter(t => t.id != objList.id)
    addressList.unshift(objList)
    currentAddressList.value.unshift(objList)
    localStorage.loaclAddress = JSON.stringify(addressList)
    fieldValue.value = ''
    addressee.value = ''
    telVal.value = ''
    detailedAddress.value = ''
    currentDefaultVal.value = false
    // showAddressPopup.value = false
    addAddress.value = false

}

const setDefault = (id: number) => {
    let objList = localStorage.loaclAddress ? JSON.parse(localStorage.loaclAddress) : []
    objList.map(item => {
        if (item.id == id) {
            item.default = true
            objList = objList.filter(t => t.id != item.id)
            objList.unshift(item)
        } else {
            item.default = false
        }
    })

    currentAddressList.value.map(item => {
        if (item.id == id) {
            item.default = true
            currentAddressList.value = currentAddressList.value.filter(t => t.id != item.id)
            currentAddressList.value.unshift(item)
        } else {
            item.default = false
        }
        if (item.default) {
            currentDefault.value = item
            currentId.value = item.id
        }
    })
    localStorage.loaclAddress = JSON.stringify(objList)

}

const currentId = ref()
// 当前地址,没有选择的话是默认地址
const currentDefault = ref()

const setCurrentDefault = (list: Address) => {
    currentDefault.value = list
    showAddressPopup.value = false
    currentId.value = list.id
}

// 重新修改内容
const setAddress = (list: Address) => {
    // let objList = localStorage.loaclAddress ? JSON.parse(localStorage.loaclAddress) : []
    // objList = objList.filter(t=>t.id!=list.id)

    fieldValue.value = list.fieldValue
    addressee.value = list.addressee
    telVal.value = list.telVal
    detailedAddress.value = list.detailedAddress
    currentDefaultVal.value = list.default
    addAddress.value = true
}

const delAddress = (id: number) => {
    currentAddressList.value = currentAddressList.value.filter(t => t.id != id)
    localStorage.loaclAddress = JSON.stringify(currentAddressList.value)
    showToast('删除成功');
}


// 提交订单 转到支付页面
const paymentPopup = ref(false)


const paymentMode = ref('支付宝')
const paymentModeSheet = ref(false)
const actions = [
    { name: '支付宝' },
    { name: '微信' },
    { name: '银行卡' },
];
const onSelect = (item) => {
    paymentModeSheet.value = false;
    paymentMode.value = item.name
};
// 支付密码
const passwordVal = ref()
const showKeyboard = ref(true)
const isShowSheet = ref(false)

watch(() => passwordVal.value, (n) => {
    if (n.length >= 6) {
        console.log(n);

        if (n == '258036') {
            showSuccessToast('支付成功');
            showKeyboard.value = false
            isShowSheet.value = false
            passwordVal.value = ''
            goToOrderList(2,2,'待发货')
        } else {
            passwordVal.value = ''
            showFailToast('密码错误')
        }

    }
})

const { addBePaidList } = useOrderListStore()
const goToOrderList = (orderId:number,expiredNotType:number,typeText:string) => {
    paymentPopup.value = false
    curremtList.value.map(item=>{
        addBePaidList({...item, type:orderId,id:Date.now(),expiredNotType:expiredNotType,typeText:typeText})

    })
    router.replace({
        name: 'orderlist',
        params: {
            id: orderId
        }
    })
}
</script>

<template>
    <div class="order-view">
        <div class="order-nav-bar">
            <van-nav-bar>
                <template #left>
                    <van-icon @click="router.go(-1)" name="arrow-left" size="22" color="#c5aa92" />
                </template>
                <template #title>
                    <span class=" text-gray-600">确认订单</span>
                </template>
                <template #right>
                    <van-icon @click="router.push('/shoppingcart')" name="cart-o" size="22" color="#c5aa92" />
                </template>
            </van-nav-bar>
            <van-notice-bar color="#ff5475" background="#ffe6e8">
                温馨提示：下载App，及时跟进订单信息哟！
            </van-notice-bar>
        </div>

        <div class="address flex justify-between items-center p-3 bg-white" @click="showAddressPopup = !showAddressPopup">
            <div class="address-left flex items-center">
                <i class="mr-2"><van-icon size="22" name="location-o" /></i>
                <span v-show="!currentDefault">请填写收货地址</span>
                <div v-show="currentDefault" class="selected-address">
                    <span>{{ currentDefault?.addressee }} {{ currentDefault?.telVal }}</span>
                    <p>{{ currentDefault?.fieldValue }}{{ currentDefault?.detailedAddress }}</p>
                </div>
            </div>
            <van-icon size="22" name="arrow" />
        </div>

        <van-popup v-model:show="showAddressPopup" position="bottom" :style="{ height: '80%' }">

            <div class="address-list w-full h-full bg-slate-50" style="background-color: #f6f6f6;">

                <div class="address-list p-3 pb-12">
                    <OrderAddressee @delAddress="delAddress" @setAddress="setAddress" :currentId="currentId"
                        @setCurrentDefault="setCurrentDefault" @setDefault="setDefault" v-for="c in currentAddressList"
                        :list="c" :key="c.id">
                    </OrderAddressee>
                </div>


                <div @click="addAddress = !addAddress"
                    class="add-btn w-full text-center py-2 border-t-2 border-gray-200 fixed bottom-0 text-red-400 bg-white">
                    + 新增地址
                </div>
            </div>

            <van-popup v-model:show="addAddress" position="right"
                :style="{ width: '100%', height: '100%', backgroundColor: '#f6f6f6' }">
                <div class=" text-center py-2">添加地址</div>
                <div class="add-address w-full my-3">
                    <van-field v-model.trim="addressee" label="收件人" />
                    <van-field v-model.trim="telVal" type="tel" label="手机号" />
                    <van-field v-model.trim="fieldValue" is-link readonly label="地区" placeholder="请选择所在地区"
                        @click="show = true" />
                    <van-field v-model.trim="detailedAddress" label="详细地址" />


                    <van-popup v-model:show="show" round position="bottom">
                        <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="options" @close="show = false"
                            @finish="onFinish" />
                    </van-popup>

                    <div class="btns flex justify-between mt-2">
                        <span class=" w-1/2 text-center py-3 bg-gray-200" @click="addAddress = !addAddress">取消</span>
                        <span class=" w-1/2 text-center py-3 bg-red-400" @click="addAddressFn">确认</span>
                    </div>
                </div>

            </van-popup>


        </van-popup>


        <div class="order-content bg-white mt-4 py-2">
            <div class="comp-list pb-2 border-b-2 border-gray-100">
                <ProductCard v-for=" (l, i) in curremtList" :key="i" :list="l" :type="'order'"></ProductCard>
            </div>

            <div class="order-text text-black text-sm p-2">

                <div class="flex justify-between py-2">
                    <span>数量</span>
                    <span>x{{ currentNum }}</span>
                </div>

                <div class="flex justify-between py-2">
                    <span>意外换新</span> <span class=" flex text-gray-400">衣服出现意外破损可换新 <i
                            class=" w-4 h-4 rounded-full ml-1"><img src="../../assets/orderImg/wenhao.png" alt=""></i>
                    </span> <input type="checkbox">
                </div>
                <div class="flex justify-between py-2">
                    <span>退货补运费</span> <span>商家赠送<van-icon name="arrow" /></span>
                </div>
                <div class="flex justify-between py-2">
                    <span>延误必赔</span> <span>商家赠送<van-icon name="arrow" /></span>
                </div>
                <div class="flex justify-between items-center py-2">
                    <span>订单备注</span> <span class=" w-4/5 bg-gray-100 p-2"><input class=" w-full bg-gray-100" type="text"
                            placeholder="有什么想对商家说的可以写在这里哦~"></span>
                </div>

                <div class="flex justify-end py-2">
                    <span class=" text-xs text-gray-400 mr-1">共{{ curremtList.num }}件</span> <span class=" font-bold">店铺合计:
                        <b class=" text-red-400">￥{{ currentPrice.toFixed(2) }}</b></span>
                </div>
            </div>
        </div>

        <div class="place-order w-full bg-white flex justify-between items-center fixed bottom-0 left-0">
            <span class="px-2">
                总价: <b class=" text-red-400 text-base"> <i class="text-xs">￥</i> {{
                    currentPrice.toFixed(2) }}</b>
            </span>

            <div class="right-place flex items-center">
                <span class=" text-xs text-gray-400 mr-2">共{{ curremtList.num }}件商品</span>
                <span class="p-4 bg-red-500 text-white" @click="paymentPopup = !paymentPopup">提交订单</span>
            </div>

            <van-popup v-model:show="paymentPopup" position="bottom" :style="{ height: '60%' }">

                <div class="content px-3 text-gray-400">

                    <div class="top flex justify-between items-center  py-3 border-b-2 border-gray-100">
                        <span @click="goToOrderList(1,1,'待付款')">X</span>
                        <span>收银台</span>
                        <span> <img class=" w-4 h-4 rounded-full" src="../../assets/orderImg/wenhao.png" alt=""></span>
                    </div>

                    <div class="mode flex justify-between py-3 border-b-2 border-gray-100">
                        <span>支付方式</span>
                        <span @click="paymentModeSheet = !paymentModeSheet">{{ paymentMode }}
                            <van-icon name="arrow" />
                        </span>

                        <van-action-sheet v-model:show="paymentModeSheet" :actions="actions" @select="onSelect" />

                    </div>


                    <div class="payment-amount flex justify-between py-3">
                        <span>支付金额</span>
                        <span class=" text-xl text-black">{{ currentPrice.toFixed(2)}}元</span>
                    </div>

                    <div @click="paymentPopup = !paymentPopup, isShowSheet = !isShowSheet"
                        class="confirm-payment w-11/12 text-center py-2 pr-2 bg-red-400 text-white text-lg fixed bottom-0 left-3">

                        确认支付

                    </div>


                </div>

            </van-popup>

            <div class="password w-full h-full z-10  fixed left-0 top-20" v-show="isShowSheet"
                style=" background-color: rgba(0,0,0,.3);">
                <!-- 密码输入框 -->
                <van-password-input :value="passwordVal" :focused="showKeyboard" @focus="showKeyboard = true" />
                <!-- 数字键盘 -->
                <van-number-keyboard v-model="passwordVal" :show="showKeyboard"
                    @blur="showKeyboard = false, isShowSheet = false" />
            </div>

        </div>
    </div>
</template>


<style lang="scss" scoped>
.order-view {
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    background-color: #f6f6f6;
    z-index: 10;
    overflow-y: auto;
}
</style>